<template>
	<div class="dorm-list">
        <nav-header>
			<template slot="menuBefore">
				<li><router-link to="/life/dormitory/accommodation-list" tag="a">住宿管理</router-link></li>
				<li class="gap">&gt;</li>
			</template>
			<li>{{buidingTitle}}</li>
		</nav-header>

        <div class="building-fixed-btn">
            <span class="add-floor-btn" @click="newFloor('add')">添加楼层</span>
        </div>

        <div class="building-content" v-loading="loading.status" :element-loading-text="loading.txt">
            <div class="building-list" v-for="(item1, inx1) in listData" :key="inx1">
                <div class="building-floor-name">
                    <div>
                        <span>{{item1.name}}</span>
                        <i class="el-icon-edit" @click="newFloor(item1)"></i>
                    </div>
                    <div>
                        <el-button type="primary" v-show="inx1 > 0" @click="moveUp(item1, inx1)">上移</el-button>
                        <el-button type="primary" v-show="inx1 < listData.length - 1" @click="moveDown(item1, inx1)">下移</el-button>
                        <el-button type="danger" @click="deleteConfirmFloor(item1)">删除</el-button>
                    </div>
                </div>

                <div class="building-floor-box">
                    <div class="building-item" v-for="(item2, inx2) in item1.dormitory" :key="inx2">
                        <div>
                            <span>{{item2.number}}</span>
                            <div class="item-point">
                                <span>...</span>
                                <div @click.stop.prevent="() => false">
                                    <span @click="newRoom(item2)">编辑</span>
                                    <span @click="deleteRoomConfirm(item2, inx2)">删除</span>
                                </div>
                            </div>
                        </div>
                        <span>床位数：{{item2.bednum}}</span>
                        <template v-if="item2.property">
                            <div class="room-asset-list" v-if="item2.property.length <= 6">
                                <span v-for="(item3, inx3) in item2.property" :key="inx3">{{item3.name}}</span>
                            </div>
                            <el-carousel 
                                v-else
                                arrow="always" 
                                height="75px"
                                :autoplay="false">
                                <el-carousel-item class="room-asset-list" v-for="(itemn, index1) in Math.ceil(item2.property.length/6)" :key="index1">
                                    <span v-for="(item3, inx3) in item2.property.filter((val, index) => (index < 6 * index1 + 6) && (index >= 6 * index1))" :key="inx3">{{item3.name}}</span>
                                </el-carousel-item>
                            </el-carousel>
                        </template>
                    </div>
                    <div class="building-item">
                        <i class="el-icon-plus" @click="newRoom('add', item1.id)"></i>
                    </div>
                </div>
            </div>
        </div>

        <el-dialog 
            :title="floorTitle" 
            :visible.sync="floorVisible" 
            class="add-floor-manage" 
            width="550px" 
            :before-close="cancelForm"
            :close-on-click-modal="false">
            <el-form :model="floorForm" :rules="rules" ref="floorForm" label-width="100px" class="demo-floor-form">
                <el-form-item label="楼层名称：" prop="floorName">
                    <el-input v-model.trim="floorForm.floorName" placeholder="示例：二楼/2F" maxLength="8"></el-input>
                </el-form-item>
            </el-form>
            
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancelForm" plain>取消</el-button>
                <el-button type="primary" @click="submitFloor('floorForm')">确定</el-button>
            </div>
        </el-dialog>

        <el-dialog 
            :title="roomTitle" 
            :visible.sync="roomVisible" 
            class="add-room-manage" 
            width="550px" 
            :before-close="cancelForm"
            :close-on-click-modal="false">
            <el-form :model="roomForm" :rules="rules" ref="roomForm" label-width="100px" class="demo-room-form">
                <el-form-item label="寝室号：" prop="number">
                    <el-input v-model.trim="roomForm.number" placeholder="示例：405" maxLength="8"></el-input>
                </el-form-item>
                <el-form-item label="床位数：" prop="count">
                    <el-input-number 
                        class="input-number-text"
                        v-model="roomForm.count" 
                        controls-position="right" 
                        :min="1" 
                        :max="20"
                        :precision="0"
                        placeholder="示例：4">
                    </el-input-number>
                </el-form-item>
                <el-form-item label="资产：" class="asset-checkbox">
                    <el-checkbox-group v-model="roomForm.asset">
                        <el-checkbox 
                            v-for="(item, inx) in assetList" 
                            :key="inx" 
                            :label="item.name" 
                            name="type">
                        </el-checkbox>
                    </el-checkbox-group>
                    <span @click="newAsset">编辑</span>
                </el-form-item>
            </el-form>
            
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancelForm" plain>取消</el-button>
                <el-button type="primary" @click="submitRoom('roomForm')">确定</el-button>
            </div>
        </el-dialog>

        <el-dialog 
            title="编辑" 
            :visible.sync="assetVisible" 
            class="add-asset-manage" 
            width="580px" 
            :before-close="cancelAssetForm"
            :close-on-click-modal="false">
            <div class="asset-list">
                <div v-for="(item, inx) in assetList" :key="inx">
                    <span>{{item.name}}</span>
                    <i class="el-icon-close" @click="deleteAsset(inx)"></i>
                </div>
            </div>
            <div class="add-asset-box">
                <el-input v-model.trim="assetVal" maxLength="4" placeholder="请输入内容"></el-input>
                <el-button type="primary" @click="submitAsset">添加</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            roomVisible: false, // 添加/编辑宿舍弹窗
            floorVisible: false, // 添加楼层表单是否可见
            assetVisible: false, // 编辑资产表单
            assetVal: '', // 要添加的资产信息
            roomTitle: '添加宿舍', // 添加/编辑宿舍弹窗标题
            floorTitle: '添加楼层', // 添加楼层标题
            buidingTitle: '', // 宿舍楼名称
            listData: [], // 宿舍列表
            assetList: [], // 资产列表
            floorForm: { // 楼层信息表单
                floorId: null,
                floorName: '' // 楼层名称
            },
            roomForm: { // 宿舍信息表单
                id: null,
                number: '', // 寝室号
                count: '1', // 床位数
                asset: [] // 资产
            },
            loading: { // loading 状态
                status: false,
                txt: '获取数据...'
            },
            rules: {
                floorName: [
                    { required: true, message: '请输入楼层名称', trigger: 'blur' },
                    { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
                ],
                number: [
                    { required: true, message: '请输入寝室号', trigger: 'blur' }
                ],
                count: [
                    { required: true, message: '请输入床位数', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getList();
        this.getAssetList();
        this.getBuildingName();
    },
    mounted() {
        document.querySelector('.el-main').addEventListener('scroll', this.mainScroll);
    },
    beforeDestroy() {
        document.querySelector('.el-main').removeEventListener('scroll', this.mainScroll);
    },
    methods: {
        /**
         * 获取宿舍楼名称
         */
        getBuildingName() {
            let success = (res => {
                this.buidingTitle = res.data.name;
            })

            this.$ajax.get('api/dormitory/dormitoryBuilding', {params: {id: this.$route.params.id}, func:{success: success}});
        },
        /**
         * 获取资产列表
         */
        getAssetList() {
            let success = (res => {
                this.assetList = res.data;
            })

            this.$ajax.get('api/dormitory/dormitoryProperty',{params: {}, func:{success: success}});
        },
        /**
         * 添加滚动事件，添加楼层按钮固定在顶部
         */
        mainScroll() {
            let elMailDom = document.querySelector('.el-main');
            let dom = document.querySelector('.dorm-list .building-fixed-btn').classList;

            if (elMailDom.scrollTop > 51) {
                dom.add('buiding-fixed-active');
            } else {
                dom.remove('buiding-fixed-active');
            }
        },
        /**
         * 获取寝室列表
         */
        getList() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.listData = res.data;
            })

            this.$ajax.get('api/dormitory/dormitory',{params: {building_id: this.$route.params.id}, func:{success: success}});
        },
        /**
         * 添加/编辑楼层
         * @param {String/Object} val 添加标识/楼层信息
         */
        newFloor(val) {
            this.floorVisible = true;

            if (val === 'add') {
                this.floorTitle = '添加楼层';
                this.floorForm.floorId = null;
                this.floorForm.floorName = '';
            } else {
                this.floorTitle = '编辑楼层';
                this.floorForm.floorId = val.id;
                this.floorForm.floorName = val.name;
            }

            this.$nextTick(() => {
                this.$refs.floorForm.clearValidate();
            })
        },
        /**
         * 保存楼层名称
         * @param {String} formName 楼层表单 ref
         */
        submitFloor(formName) {
             this.$refs[formName].validate((valid) => {
                if (valid) {
                    let flag = false;
                    !is_empty(this.listData) && this.listData.forEach(item => {
                        if (item.name === this.floorForm.floorName) {
                            flag = true;
                        }
                    })

                    if (flag) {
                        this.$message.error('楼层名不能重复');
                        return false;
                    }

                    const success = (res => {
                        this.$message.success(res.msg);
                        this.floorVisible = false;

                        this.getList();
                    })

                    if (this.floorForm.floorId) {
                        let param1s = {
                            id: this.floorForm.floorId,
                            name: this.floorForm.floorName
                        }
                        this.$ajax.put("api/dormitory/dormitoryFloor", param1s, {func: {success: success}});
                    } else {
                        let params = {
                            name: this.floorForm.floorName,
                            building_id: this.$route.params.id,
                            create_id: this.$g.user_id,
                            sort: (!is_empty(this.listData) ? this.listData.length : 0) + 1, // 楼层数量
                        }
                        this.$ajax.post("api/dormitory/dormitoryFloor", params, {func: {success: success}});
                    }

                } else {
                    return false;
                }
            });
        },
        /**
         * 移除表单弹窗
         */
        cancelForm() {
            this.roomVisible = false;
            this.floorVisible = false;
        },
        /**
         * 确认是否删除楼层
         * @param {Object} item 楼层信息
         */
        deleteConfirmFloor(item) {
            let yes = (res => {
                this.deleteFloor(item.id);
            })
            let cancel = (res => {})

            this.e_confirm({yes: yes, cancel: cancel, txt:`该操作将会删除${this.buidingTitle}${item.name}内所有宿舍，请确认本次操作`});
        },
        /**
         * 删除数据
         * @param {String} id 删除的 id
         */
        deleteFloor(id) {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.$message.success(res.msg);

                this.getList();
            });
            let fail = (res =>{
                this.loading.status = false;
                this.$message.error(res.msg);

                this.getList();
            }) 
            
            this.$ajax.delete('api/dormitory/dormitoryFloor', {params: {id}, func: {success: success, fail: fail}})
        },
        /**
         * 楼层上移
         * @param {Object} item 楼层信息
         * @param {Number} inx 数组下标
         */
        moveUp(item, inx) {
            let yes = (res => {
                this.moveFloor(item.id, inx, 1);
            })
            let cancel = (res => {})

            this.e_confirm({yes: yes, cancel: cancel, txt:'确定将 ' + item.name + ' 上移吗？'});
        },
        /**
         * 楼层下移
         * @param {Object} item 楼层信息
         * @param {Number} inx 数组下标
         */
        moveDown(item, inx) {
            let yes = (res => {
                this.moveFloor(item.id, inx, 2);
            })
            let cancel = (res => {})

            this.e_confirm({yes: yes, cancel: cancel, txt:'确定将 ' + item.name + ' 下移吗？'});
        },
        /**
         * 楼层移动
         * @param {Number} id 楼层 id
         * @param {Number} flag 1 上移 || 2 下移
         */
        moveFloor(id, inx, flag) {
            const success = (res => {
                this.$message.success(res.msg);

                this.getList();
            })
            const fail = (res => {
                this.$message.error(res.msg);

                this.getList();
            })

            let params = {
                id,
                sort_type: flag
            }

            this.$ajax.put("api/dormitory/dormitoryFloor", params, {func: {success: success}});
        },
        /**
         * 确认删除宿舍
         * @param {object} item 宿舍信息
         * @param {Number} inx 数组下标
         */
        deleteRoomConfirm(item, inx) {
            let yes = (res => {
                this.deleteRoom(item.id);
            })
            let cancel = (res => {})

            this.e_confirm({yes: yes, cancel: cancel, txt:`是否删除${this.buidingTitle}${item.number}宿舍？`});
        },
        /**
         * 删除宿舍
         * @param {Number} id 宿舍id
         */
        deleteRoom(id) {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.$message.success(res.msg);

                this.getList();
            });
            let fail = (res =>{
                this.loading.status = false;
                this.$message.error(res.msg);

                this.getList();
            }) 
            
            this.$ajax.delete('api/dormitory/dormitory', {params: {id}, func: {success: success, fail: fail}})
        },
        /**
         * 添加/编辑宿舍
         * @param {String/Object} val 添加标识/宿舍信息
         * @param {Number} id 楼层 id 
         */
        newRoom(val, id) {
            this.roomVisible = true;

            if (val === 'add') {
                this.roomTitle = '添加宿舍';
                this.addFloorId = id;
                this.roomForm = {
                    id: null,
                    number: '',
                    count: '1',
                    asset: []
                }
            } else {
                this.roomTitle = '编辑宿舍';
                let temp = [];
                if (!is_empty(val.property)) {
                    val.property.forEach(item => {
                        temp.push(item.name)
                    })
                }

                this.roomForm = {
                    id: val.id,
                    number: val.number,
                    count: val.bednum,
                    asset: temp
                }
            }

            this.$nextTick(() => {
                this.$refs.roomForm.clearValidate();
            })
        },
        /**
         * 保存宿舍信息
         * @param {String} formName 宿舍表单 ref
         */
        submitRoom(formName) {
             this.$refs[formName].validate((valid) => {
                if (valid) {
                    let flag = false;
                    let flag1 = false;

                    !is_empty(this.listData) && this.listData.forEach(item => {
                        !is_empty(item.dormitory) && item.dormitory.forEach(item1 => {
                            if (item1.number === this.roomForm.number) {
                                flag = true;
                            }

                            if (item1.id != this.roomForm.id) {
                                if (item1.number === this.roomForm.number) {
                                    flag1 = true;
                                }
                            }
                        })
                    })

                    if (flag) {
                        if (this.roomForm.id) {
                            if (flag1) {
                                this.$message.error('寝室名称不能重复');
                                return false;
                            }
                        } else {
                            this.$message.error('寝室名称不能重复');
                            return false;
                        }
                    }

                    const success = (res => {
                        this.roomVisible = false;

                        this.getList();
                    })

                    let temp = [];

                    if (!is_empty(this.roomForm.asset)) {
                        this.assetList.forEach(item => {
                            if (this.roomForm.asset.includes(item.name)) {
                                temp.push(item.id);
                            }
                        })
                    }

                    if (this.roomForm.id) {
                        let params = {
                            id: this.roomForm.id,
                            number: this.roomForm.number,
                            bednum: this.roomForm.count,
                            property_id: temp
                        }
                        this.$ajax.put("api/dormitory/dormitory", params, {func: {success: success}});
                    } else {
                        let params = {
                            number: this.roomForm.number, // 寝室号
                            floor_id: this.addFloorId, // 楼层id
                            bednum: this.roomForm.count, // 床位数
                            create_id: this.$g.user_id, // 创建人id
                            property_id: temp // 资产id（一维数组）
                        }
                        this.$ajax.post("api/dormitory/dormitory", params, {func: {success: success}});    
                    }

                } else {
                    return false;
                }
            });
        },
        /**
         * 编辑资产信息
         */
        newAsset() {
            this.assetVisible = true;
            this.assetVal = '';
        },
        /**
         * 取消资产编辑
         */
        cancelAssetForm() {
            this.assetVisible = false;
        },
        /**
         * 删除资产信息
         * @param {Number} inx 数组下标
         */
        deleteAsset(inx) {
            let success = (res => {
                let name = this.assetList[inx].name;
                this.assetList.splice(inx, 1);
                this.$message.success(res.msg);

                this.getAssetList();

                this.listData.forEach(item1 => {
                    !is_empty(item1.dormitory) && item1.dormitory.forEach(item2 => {
                        let _inx = '';
                        !is_empty(item2.property) && item2.property.forEach((item3, index3) => {
                            if (item3.name === name) {
                                _inx = index3;
                            }
                        })

                        _inx !== '' && item2.property.splice(_inx, 1);
                    })
                })
            });
            let fail = (res =>{
                this.$message.error(res.msg);
            }) 
            
            this.$ajax.delete('api/dormitory/dormitoryProperty', {params: {id: this.assetList[inx].id}, func: {success: success, fail: fail}});
        },
        /**
         * 保存资产信息
         */
        submitAsset() {
            if (this.assetVal) {
                let flag = false;
                !is_empty(this.assetList) && this.assetList.forEach(item => {
                    if (item.name === this.assetVal) {
                        flag = true;
                    }
                })

                if (flag) {
                    this.$message.error('资产名称不可以重复');
                    return false;
                }
                
                let params = {
                    name: this.assetVal
                }

                const success = (res => {
                    this.$message.success(res.msg);
                    this.assetVal = '';

                    this.getAssetList();
                })
                const fail = (res => {
                    this.$message.error(res.msg);
                })

                this.$ajax.post("api/dormitory/dormitoryProperty", params, {func: {success: success, fail: fail}});
            }
        }
    }
}
</script>

<style lang="scss">
    .dorm-list {
        .building-fixed-btn {
            margin-bottom: 25px;
            padding: 0 10px;

            .add-floor-btn {
                display: inline-block;
                width: 80px;
                height: 30px;
                line-height: 30px;
                text-align: center;
                color: #fff;
                background: #348EFC;
                border-radius: 2px;
                cursor: pointer;
            }
        }

        .buiding-fixed-active {
            position: fixed;
            top: 60px;
            margin-left: -40px;
            padding-left: 50px;
            width: 100%;
            height: 50px;
            line-height: 50px;
            background: #fff;width: 100%;
            border-top: 1px solid #e6e6e6;
            border-bottom: 1px solid #e6e6e6;
            z-index: 99;
        }

        .el-carousel {
            .el-carousel__arrow--left {
                left: -27px;
            }

            .el-carousel__arrow--right {
                right: -27px;
            }

            .el-carousel__arrow--left,
            .el-carousel__arrow--right {
                background-color: transparent;

                i {
                    color: #2C2C2C;
                    font-size: 23px;
                }
            }

            .el-carousel__indicators {
                display: none;
            }
        }

        .building-content {
            padding: 0 10px;

            .building-list {
                margin-bottom: 33px;

                .building-floor-name {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    >div:first-child {
                        span {
                            display: inline-block;
                            padding: 2px 16px;
                            font-size: 18px;
                            min-width: 78px;
                            max-width: 800px;
                            height: 30px;
                            line-height: 30px;
                            text-align: center;
                            color: #FFFFFF;
                            background: #7C95CE;
                            border-bottom-right-radius: 15px;
                            border-top-right-radius: 15px;
                            vertical-align: middle;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                            overflow: hidden;
                        }

                        i {
                            margin-left: 12px;
                            font-size: 18px;
                            cursor: pointer;
                        }
                    }

                    >div:last-child {
                        button {
                            width: 80px;
                            height: 30px;
                        }
                    }
                }

                .building-floor-box {
                    display: flex;
                    flex-wrap: wrap;
                }

                .building-item {
                    margin-top: 23px;
                    margin-right: 20px;
                    width: 390px;
                    height: 180px;
                    border: 1px solid #DDDDDD;
                    border-radius: 4px;
                    box-sizing: border-box;

                    >div:first-child {
                        position: relative;
                        display: flex;
                        justify-content: space-between;
                        padding: 7px 20px;
                        font-size: 18px;
                        background: #FBF6D4;

                        .item-point {
                            position: relative;
                            text-align: right;
                            font-size: 25px;
                            color: #999;
                            line-height: 0;
                            letter-spacing: 1px;
                            cursor: pointer;

                            >span {
                                padding: 0 0 10px 15px;
                            }

                            div:before {
                                content: '';
                                display: block;
                                position: absolute;
                                top: -4px;
                                right: 7px;
                                width: 10px;
                                height: 10px;
                                background: #fff;
                                transform: rotate(45deg);
                                box-shadow: 0 2px 4px 0 rgba(238,220,214,0.50);
                            }

                            div {
                                position: absolute;
                                right: 0;
                                top: 20px;
                                padding: 10px 0;
                                font-size: 12px;
                                width: 74px;
                                height: 63px;
                                line-height: 23px;
                                background: #FFFFFF;
                                box-shadow: 0 2px 4px 0 rgba(238,220,214,0.50);
                                box-sizing: border-box;
                                transform: scale(0);
                                transform-origin: 100% 0%;
                                visibility: hidden;
                                transition: all 0.3s linear;

                                span {
                                    display: block;
                                    font-size: 12px;
                                    text-align: center;
                                }

                                span:hover {
                                    background: #CFE9FF;
                                }

                                span:first-child {
                                    color: #333;
                                }

                                span:last-child {
                                    color: #CC3445;
                                }
                            }
                        }

                        .item-point:hover {
                            div {
                                transform: scale(1);
                                visibility: visible;
                            }
                        }

                        >span:first-child {
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                        }
                    }

                    >span {
                        display: inline-block;
                        margin-top: 21px;
                        margin-bottom: 18px;
                        padding: 0 20px;
                        font-size: 12px;
                        color: #333;
                    }

                    >div:last-child {
                        padding: 0 20px 7px;
                    }
                }

                .building-item:last-child {
                    display: flex;
                    justify-content: center;
                    align-items: center;

                    i {
                        width: 100px;
                        height: 100px;
                        line-height: 100px;
                        text-align: center;
                        font-size: 36px;
                        color: #81B1E0;
                        background: #F4F9FF;
                        border: 1px dashed #7A9BB6;
                        border-radius: 4px;
                        cursor: pointer;
                    }
                }

                .room-asset-list {
                    span {
                        display: inline-block;
                        margin-right: 10px;
                        margin-bottom: 15px;
                        width: 109px;
                        height: 30px;
                        line-height: 30px;
                        text-align: center;
                        border: 1px solid #DDDDDD;
                        border-radius: 4px;
                        box-sizing: border-box;
                    }

                    span:nth-child(3n) {
                        margin-right: 0;
                    }
                }
            }
        }

        .input-number-text {
            width: 100%;

            >span {
                display: none;
            }

            input {
                text-align: left;
            }
        }

        .asset-checkbox {
            .el-checkbox-group {
                .el-checkbox+.el-checkbox {
                    margin-left: 0;
                }

                label {
                    margin-right: 30px;
                }
            }

            .el-form-item__content {
                >span {
                    display: inline-block;
                    margin-top: 10px;
                    width: 90px;
                    height: 30px;
                    line-height: 30px;
                    color: #348EFC;
                    text-align: center;
                    border: 1px solid #9AC7FF;
                    border-radius: 4px;
                    box-sizing: border-box;
                    cursor: pointer;
                }
            }
        }

        .add-asset-manage {
            .add-asset-box {
                display: flex;
                padding-bottom: 36px;

                button {
                    margin-left: 20px;
                }
            }

            .asset-list {
                display: flex;
                flex-wrap: wrap;
                margin-bottom: 25px;

                >div {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-right: 10px;
                    margin-bottom: 15px;
                    padding: 0 10px;
                    width: 120px;
                    height: 30px;
                    line-height: 30px;
                    text-align: center;
                    border: 1px solid #DDDDDD;
                    border-radius: 4px;
                    box-sizing: border-box;

                    i {
                        cursor: pointer;
                    }
                }
            }
        }
    }
</style>